<template>
  <view class="container">
    <scroll-view class="form-content" scroll-y :show-scrollbar="false">
      <!-- 基础信息 -->
      <view class="form-card">
        <view class="section-title">账户信息</view>
        
        <view class="form-item">
          <text class="item-label">登录账号</text>
          <input 
            v-model="registerForm.username"
            placeholder="请输入登录账号"
            class="form-input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="item-label">登录密码</text>
          <input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入登录密码（8-20位）"
            class="form-input"
            maxlength="20"
          />
        </view>

        <view class="form-item">
          <text class="item-label">确认密码</text>
          <input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            class="form-input"
            maxlength="20"
          />
        </view>
      </view>

      <!-- 负责人信息 -->
      <view class="form-card">
        <view class="section-title">负责人信息</view>
        
        <view class="form-item">
          <text class="item-label">负责人姓名</text>
          <input 
            v-model="registerForm.principal"
            placeholder="请输入负责人真实姓名"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">身份证号</text>
          <input 
            v-model="registerForm.idNumber"
            placeholder="请输入18位身份证号码"
            class="form-input"
            type="idcard"
            maxlength="18"
          />
        </view>

        <view class="form-item">
          <text class="item-label">联系电话</text>
          <view class="input-group">
            <input
              v-model="registerForm.phone"
              placeholder="请输入11位手机号码"
              class="form-input"
              type="number"
              maxlength="11"
            />
            <button 
              class="sms-btn"
              :disabled="smsDisabled"
              @click="getSmsCode"
            >
              {{ smsText }}
            </button>
          </view>
        </view>

        <view class="form-item" v-if="captchaEnabled">
          <text class="item-label">短信验证码</text>
          <input 
            v-model="registerForm.smsCode"
            placeholder="请输入6位验证码"
            class="form-input"
            type="number"
            maxlength="6"
          />
        </view>
      </view>

      <!-- 店铺信息 -->
      <view class="form-card">
        <view class="section-title">店铺信息</view>
        
        <view class="form-item">
          <text class="item-label">店铺名称</text>
          <input 
            v-model="registerForm.shopName"
            placeholder="请输入工商注册名称"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">营业执照号</text>
          <input 
            v-model="registerForm.licenseNo"
            placeholder="请输入15位营业执照编号"
            class="form-input"
            maxlength="15"
          />
        </view>

        <view class="form-item">
          <text class="item-label">经营区域</text>
          <picker 
            mode="region" 
            @change="handleRegionChange"
            class="form-input"
          >
            <text>{{ registerForm.region.join(' ') || '请选择所在地区' }}</text>
          </picker>
        </view>

        <view class="form-item">
          <text class="item-label">详细地址</text>
          <input 
            v-model="registerForm.address"
            placeholder="请输入店铺详细地址"
            class="form-input"
          />
        </view>

        <view class="form-item">
          <text class="item-label">商家介绍</text>
          <textarea
            v-model="registerForm.description"
            placeholder="请输入商家简介（200字以内）"
            class="form-textarea"
            maxlength="200"
          />
          <text class="word-count">{{ registerForm.description.length }}/200</text>
        </view>
      </view>

      <!-- 证照上传 -->
      <view class="form-card">
        <view class="section-title">证照上传</view>
        
        <view class="upload-grid">
          <!-- 身份证人像面 -->
          <view class="upload-item">
            <text class="upload-label">身份证人像面</text>
            <view class="upload-box" @click="uploadFile('idCardFront')">
              <image 
                v-if="registerForm.idCardFront" 
                :src="registerForm.idCardFront" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" color="#007AFF" />
              </view>
              <view 
                v-if="registerForm.idCardFront" 
                class="delete-icon"
                @click.stop="registerForm.idCardFront = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 身份证国徽面 -->
          <view class="upload-item">
            <text class="upload-label">身份证国徽面</text>
            <view class="upload-box" @click="uploadFile('idCardBack')">
              <image 
                v-if="registerForm.idCardBack" 
                :src="registerForm.idCardBack" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" color="#007AFF" />
              </view>
              <view 
                v-if="registerForm.idCardBack" 
                class="delete-icon"
                @click.stop="registerForm.idCardBack = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 营业执照 -->
          <view class="upload-item">
            <text class="upload-label">营业执照</text>
            <view class="upload-box" @click="uploadFile('licenseImage')">
              <image 
                v-if="registerForm.licenseImage" 
                :src="registerForm.licenseImage" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" color="#007AFF" />
              </view>
              <view 
                v-if="registerForm.licenseImage" 
                class="delete-icon"
                @click.stop="registerForm.licenseImage = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>

          <!-- 门店实景 -->
          <view class="upload-item">
            <text class="upload-label">门店实景</text>
            <view class="upload-box" @click="uploadFile('shopImage')">
              <image 
                v-if="registerForm.shopImage" 
                :src="registerForm.shopImage" 
                class="preview-image"
                mode="aspectFill"
              />
              <view v-else class="upload-placeholder">
                <uni-icons type="plus" size="48" color="#007AFF" />
              </view>
              <view 
                v-if="registerForm.shopImage" 
                class="delete-icon"
                @click.stop="registerForm.shopImage = ''"
              >
                <uni-icons type="close" size="20" color="#fff" />
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 注册按钮 -->
    <button 
      class="submit-btn"
      :class="{ disabled: !formValid }"
      @click="handleRegister"
    >
      立即注册
    </button>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getCodeImg, register } from '@/api/login'

// 响应式数据
const captchaEnabled = ref(true)
const codeUrl = ref('')
const smsText = ref('获取验证码')
const smsDisabled = ref(false)
let countdown = 60

const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  principal: '',
  idNumber: '',
  phone: '',
  smsCode: '',
  shopName: '',
  licenseNo: '',
  region: [],
  address: '',
  description: '',
  idCardFront: '',
  idCardBack: '',
  licenseImage: '',
  shopImage: '',
  uuid: ''
})

// 表单验证
const formValid = computed(() => {
  const requiredFields = [
    registerForm.value.username,
    registerForm.value.password,
    registerForm.value.confirmPassword,
    registerForm.value.principal,
    registerForm.value.idNumber,
    registerForm.value.phone,
    registerForm.value.shopName,
    registerForm.value.licenseNo,
    registerForm.value.address,
    registerForm.value.idCardFront,
    registerForm.value.idCardBack,
    registerForm.value.licenseImage
  ]
  return requiredFields.every(v => !!v) && 
    registerForm.value.password === registerForm.value.confirmPassword &&
    (captchaEnabled.value ? !!registerForm.value.smsCode : true)
})

// 获取验证码
const getSmsCode = () => {
  if (!/^1[3-9]\d{9}$/.test(registerForm.value.phone)) {
    return uni.showToast({ title: '手机号格式错误', icon: 'none' })
  }
  
  smsDisabled.value = true
  const timer = setInterval(() => {
    countdown--
    smsText.value = `${countdown}s`
    
    if (countdown <= 0) {
      clearInterval(timer)
      smsText.value = '重新获取'
      smsDisabled.value = false
      countdown = 60
    }
  }, 1000)
}

// 图片上传
const uploadFile = async (field) => {
  try {
    const res = await uni.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed']
    })
    registerForm.value[field] = res.tempFiles[0].tempFilePath
  } catch (error) {
    console.log('上传取消', error)
  }
}

// 地区选择
const handleRegionChange = (e) => {
  registerForm.value.region = e.detail.value
}

// 注册提交
const handleRegister = async () => {
  if (!formValid.value) return

  const validations = [
    { condition: !/^[\u4e00-\u9fa5]{2,10}$/.test(registerForm.value.principal), msg: '请输入2-10位中文姓名' },
    { condition: !/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(registerForm.value.idNumber), msg: '身份证格式不正确' },
    { condition: !/^\d{15}$/.test(registerForm.value.licenseNo), msg: '营业执照号应为15位数字' }
  ]

  for (const { condition, msg } of validations) {
    if (condition) return uni.showToast({ title: msg, icon: 'none' })
  }

  uni.showLoading({ title: '注册中...', mask: true })
  
  try {
    await register(registerForm.value)
    uni.hideLoading()
    uni.showModal({
      title: '注册成功',
      content: '您的商家账号已注册成功，请等待审核',
      success: () => {
        uni.reLaunch({ url: '/pages/login' })
      }
    })
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '注册失败，请重试', icon: 'none' })
  }
}

onMounted(() => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled ?? true
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      registerForm.value.uuid = res.uuid
    }
  })
})
</script>

<style lang="scss" scoped>
.container {
  background: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.form-card {
  background: #fff;
  border-radius: 16rpx;
  margin: 24rpx;
  padding: 32rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  + .form-card {
    margin-top: 32rpx;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  padding-bottom: 24rpx;
  margin-bottom: 32rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 80rpx;
    height: 4rpx;
    background: #007AFF;
  }
}

.form-item {
  margin-bottom: 48rpx;
  
  .item-label {
    display: block;
    color: #666;
    font-size: 28rpx;
    margin-bottom: 16rpx;
  }
}

.form-input {
  height: 88rpx;
  padding: 0 24rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  display: flex;
  align-items: center;
  
  &:focus-within {
    background: #fff;
    box-shadow: 0 0 0 2rpx #007AFF;
  }
}

.input-group {
  display: flex;
  gap: 16rpx;
  
  .sms-btn {
    width: 200rpx;
    height: 88rpx;
    line-height: 88rpx;
    background: #007AFF;
    color: #fff;
    border-radius: 8rpx;
    font-size: 24rpx;
    transition: all 0.2s;
    
    &[disabled] {
      background: #e0e0e0;
      color: #999;
    }
  }
}

.form-textarea {
  width: 100%;
  height: 200rpx;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.word-count {
  display: block;
  text-align: right;
  color: #999;
  font-size: 24rpx;
  margin-top: 12rpx;
}

.upload-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 32rpx;
}

.upload-item {
  .upload-label {
    display: block;
    color: #666;
    font-size: 24rpx;
    margin-bottom: 16rpx;
  }

  .upload-box {
    width: 100%;
    height: 240rpx;
    border: 2rpx dashed #007AFF;
    border-radius: 8rpx;
    position: relative;
    overflow: hidden;
    background: rgba(0,122,255,0.05);

    &.filled {
      border-color: transparent;
    }
  }

  .preview-image {
    width: 100%;
    height: 100%;
  }

  .upload-placeholder {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .delete-icon {
    position: absolute;
    top: 8rpx;
    right: 8rpx;
    width: 40rpx;
    height: 40rpx;
    background: rgba(0,0,0,0.5);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.submit-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  line-height: 100rpx;
  background: linear-gradient(135deg, #007AFF, #0051ff);
  color: #fff;
  font-size: 32rpx;
  border-radius: 0;
  transition: all 0.2s;
  
  &.disabled {
    background: #e0e0e0;
    color: #999;
  }
  
  &::after {
    border: none;
  }
  
  &:active {
    opacity: 0.9;
  }
}
</style>